package com.aivin.lib_readnotes.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;


import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.aivin.lib_base.tool.RouteUtils;
import com.aivin.lib_base.tool.WkLog;
import com.aivin.lib_widget.TextViewVertical;
import com.aivin.lib_readnotes.AppUpdateBean;
import com.aivin.lib_readnotes.R;
import com.aivin.lib_readnotes.SelectCallBack;
import com.aivin.lib_readnotes.adapter.BookAdapter;
import com.aivin.lib_widget.base.BaseActivity;
import com.aivin.lib_widget.bean.MarginDecoration;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.immersionbar.ImmersionBar;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

import com.wk.bmoblib.bean.Book;
import com.wk.bmoblib.tool.DataTool;

/**
 * 所有书本集合
 */
@Route(path = RouteUtils.BookActivity)
public class BookActivity extends BaseActivity {

    private TextViewVertical infoTv ;
    private Activity activity ;
    private TextView updateInfo ;
    private View  updateInfoLay ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImmersionBar.with(this)
                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
                .statusBarColor( R.color.color_2e4a7e)
                .init();

        activity= this ;
        initView();

        DataTool.getInstance().getBooks(findListenerBooks);
        queryUpdateInfo();
    }


private RecyclerView recyclerView ;
    private void initView(){
        updateInfoLay = findViewById(R.id.updateInfoLay) ;
        updateInfo = findViewById(R.id.updateInfo) ;

        findViewById(R.id.goUpdateBtn).setOnClickListener(onClickListener);
        infoTv = findViewById(R.id.infoTv) ;

        infoTv.setText(getString(R.string.str_isloading));
        recyclerView =  findViewById(R.id.recycle);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 1));
        recyclerView.addItemDecoration(new MarginDecoration(this));

        SwipeRefreshLayout swipeRefreshLay = findViewById(R.id.swipeRefreshLay);
        swipeRefreshLay.setEnabled(false);

        findViewById(R.id.exitActivityBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.finish();
            }
        });


    }


    private FindListener<Book>  findListenerBooks =new FindListener<Book>() {
        @Override
        public void done(List<Book> data, BmobException e) {
            if(data != null  )   {
                String info =  "︵"+ getString(R.string.app_name) +"︶" ;
                infoTv.setText(info);
                updateBooks(data);
            } else{
                infoTv.setText(getString(R.string.str_loadfailed));
            }

        }
    }  ;

    private void updateBooks(List<Book> apps){
        recyclerView.setAdapter(new BookAdapter(  apps, new SelectCallBack() {
            @Override
            public void onSelected(Object obj, int itemIndex) {
                if(obj instanceof Book ){
                    Book book = (Book) obj;
                    toGetBookChapters( book.getBookIndex() ,book.getBookName());
                }
            }
        }));
    }

    private void toGetBookChapters(int bookIndex ,String bookName){
        /*Intent intent = new Intent(this , ChapterActivity.class);
        intent.putExtra("bookIndex" ,bookIndex) ;
        intent.putExtra("bookName" ,bookName ) ;*/
        ARouter.getInstance().build(RouteUtils.ChapterActivity)
                .withInt("bookIndex", bookIndex)
                .withString("bookName", bookName)
                .navigation();

    }


    /**
     * 菜单、返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitActivity();
        }
        return false;
    }

    private long lastTime = 0 ;
    private void exitActivity( ) {
        if (System.currentTimeMillis() - lastTime < 2000L) {
            this.finish() ;
        } else {
            lastTime = System.currentTimeMillis() ;
            toastMsg(getString(R.string.str_doubleclickExit));
        }
    }


    String appUrl="" ;
    private void queryUpdateInfo( ) {
        String appPacketName =getPackageName();
        PackageInfo  pacageInfo = null;
        try {
            pacageInfo = getPackageManager().getPackageInfo(  appPacketName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        int versionCode = pacageInfo==null? 0: pacageInfo.versionCode;


        WkLog.showLog("appPacketName="+appPacketName);
        WkLog.showLog("versionCode="+versionCode);

        BmobQuery<AppUpdateBean> query = new BmobQuery< >();
        query.addWhereEqualTo("appPacketName", appPacketName);
        query.addWhereEqualTo("appVersion", versionCode);
        query.setLimit(500);
        query.findObjects( new FindListener<AppUpdateBean>() {
            @Override
            public void done(List<AppUpdateBean> object, BmobException e) {

                if(object==null){
                    return;
                }

                if(object.size()==0){
                    return;
                }

                AppUpdateBean  appUpdateBean =object.get(0) ;
                boolean hasUpdate =  appUpdateBean!=null && appUpdateBean.isMust2Update() ;
                if(hasUpdate){
                    updateInfoLay.setVisibility(View.VISIBLE);
                    updateInfo.setText(appUpdateBean.getUpdateInfo());
                    appUrl = appUpdateBean.getAppDownUrl() ;
                }

            }
        });

    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.goUpdateBtn) {
                todownApp(appUrl);
            }
        }
    };


    private void todownApp(String url){
        Uri uri = Uri.parse(url);
        Intent intent1 = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent1);
    }

}
